package cn.tsinghua.comsmacitccntsinghua.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Author yjl
 * @create 2021/10/18 21:33
 */
public class InternetWatingUtil {

    /**
     * 获取网络总流量
     * @param localUid
     * @return
     */
    public static Long getAppTotalData(int localUid){
        File dir = new File("/proc/uid_stat/");
        String[] children = dir.list();
        if(!Arrays.asList(children).contains(String.valueOf(localUid))){
            return 0L;
        }
        File uidFileDir = new File("/proc/uid_stat/"+String.valueOf(localUid));
        File uidActualFileRec = new File(uidFileDir,"tcp_rcv");
        File uidActualFileSnt = new File(uidFileDir,"tcp_snd");
        String textReceived = "0";
        String textSend = "0";
        try {
            BufferedReader bfRec = new BufferedReader(new FileReader(uidActualFileRec));
            BufferedReader bfSnd = new BufferedReader(new FileReader(uidActualFileSnt));
            String receievdLine;
            String sendLine;
            if((receievdLine = bfRec.readLine()) != null){
                textReceived = receievdLine;
            }
            if((sendLine = bfSnd.readLine()) != null){
                textSend = sendLine;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Long.valueOf(textReceived).longValue() +  Long.valueOf(textSend).longValue();
    }

    public static void writeFile(String thisData){
        File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/data.txt");
        try {
            //不存在则生成
            if(!file.exists()){
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true);
            fileWriter.write(thisData);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
